package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.bean.MainMenuBean;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WMenuDao;
import com.chhuang.ewcrm.dao.WUserMenuDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.WMenu;
import com.chhuang.ewcrm.entity.WUserMenu;
import com.chhuang.ewcrm.utils.LengthTextFilter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import javafx.beans.property.ObjectProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author chhuang
 * @create 2020-11-01-10:37
 */
public class WMenuController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(WMenuController.class);

    @FXML
    private TextField menuNameTextField;
    @FXML
    private TextField menuUrlTextField;
    @FXML
    private TextField queryMenuNameTextField;
    @FXML
    private TextField queryMenuUrlTextField;
    @FXML
    private ComboBox<MainMenuBean> parentMenuComboBox;
    @FXML
    private ComboBox<MainMenuBean> queryParentMenuComboBox;
    @FXML
    private DateTimePicker modifyTimeStartPicker;
    private ObjectProperty<LocalDateTime> modifyTimeStart;
    @FXML
    private DateTimePicker modifyTimeEndPicker;
    private ObjectProperty<LocalDateTime> modifyTimeEnd;
    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private JFXButton delJFXButton;
    @FXML
    private JFXButton seachJFXButton;
    @FXML
    private TableView<WMenu> tableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Pagination pagination;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;

    private final LengthTextFilter lengthTextFilter = new LengthTextFilter(127);

    private final WMenuDao wMenuDao = App.getSession().getMapper(WMenuDao.class);
    private final WUserMenuDao wUserMenuDao = App.getSession().getMapper(WUserMenuDao.class);

    private final QueryBean<WMenu> queryBean = new QueryBean<>();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTextFiled();
        initParentMenu();
        initDateTimePicker();
        initTableView();
        initButton();
    }

    /**
     * 初始化输入框
     */
    private void initTextFiled() {
        menuNameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        menuUrlTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        queryMenuNameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        queryMenuUrlTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
    }

    /**
     * 初始化父菜单
     */
    private void initParentMenu() {
        parentMenuComboBox.getItems().addAll(Constants.MAIN_MENUS);
        parentMenuComboBox.getSelectionModel().select(0);
        parentMenuComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(MainMenuBean mainMenuBean) {
                return mainMenuBean==null?null:mainMenuBean.getMenuName();
            }

            @Override
            public MainMenuBean fromString(String s) {
                return null;
            }
        });

        queryParentMenuComboBox.getItems().add(new MainMenuBean(-1,"请选择..."));
        queryParentMenuComboBox.getItems().addAll(Constants.MAIN_MENUS);
        queryParentMenuComboBox.getSelectionModel().select(0);
        queryParentMenuComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(MainMenuBean mainMenuBean) {
                return mainMenuBean==null?null:mainMenuBean.getMenuName();
            }

            @Override
            public MainMenuBean fromString(String s) {
                return null;
            }
        });
    }

    /**
     * 初始化日期控件
     */
    private void initDateTimePicker(){
        modifyTimeStartPicker.setPopupPreWidth(modifyTimeStartPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        modifyTimeStart = modifyTimeStartPicker.dateTimeProperty();
        modifyTimeEndPicker.setPopupPreWidth(modifyTimeEndPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        modifyTimeEnd = modifyTimeEndPicker.dateTimeProperty();
    }

    private WMenu selectMenu = new WMenu();

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("ID","menuId",false, false),
            new TableColumnBean("菜单名称","menuName",true),
            new TableColumnBean("菜单地址","fxmlUrl",true),
            new TableColumnBean("父级菜单","parentMenuId",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return Constants.MAIN_MENUS.get(Integer.parseInt(o.toString())).getMenuName();
                }
            },
            new TableColumnBean("修改时间","modifyTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            },
            new TableColumnBean("创建时间","createTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            }
    };
    private void initTableView() {
        //设置列
        List<TableColumn<WMenu, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tb : tableColumnBeans){
            TableColumn<WMenu, Object> tableColumn = new TableColumn<>(tb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tb.getRecordName()));
            tableColumn.setSortable(tb.isSort());
            tableColumn.setVisible(tb.isVisible());
            tableColumn.setCellFactory(new Callback<>() {
                @Override
                public TableCell<WMenu, Object> call(TableColumn<WMenu, Object> tableColumn) {
                    TableCell<WMenu, Object> cell = new TableCell<>() {
                        @Override
                        protected void updateItem(Object o, boolean b) {
                            super.updateItem(o, b);
                            if (b || o == null)
                                this.setText(null);
                            else
                                this.setText(tb.format(o));
                        }
                    };
                    cell.setAlignment(Pos.CENTER);
                    return cell;
                }
            });
            tableColumns.add(tableColumn);
        }
        tableView.getColumns().addAll(tableColumns);

        //设置双击某一行
        tableView.setRowFactory(wCustomerTableView -> {
            TableRow<WMenu> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    selectMenu = row.getItem();
                    menuNameTextField.setText(selectMenu.getMenuName());
                    menuUrlTextField.setText(selectMenu.getFxmlUrl());
                    parentMenuComboBox.setValue(Constants.MAIN_MENUS.get(selectMenu.getParentMenuId()));
                }
            });
            return row;
        });

        //设置排序
        tableView.setSortPolicy(wCustomerTableView -> {
            ObservableList<TableColumn<WMenu,?>> list = wCustomerTableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<WMenu,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        //每页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        pagination.setMaxPageIndicatorCount(9);//数字按钮数量
        //点击分页按钮监听
        pagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            logger.debug("pagintion+++"+queryBean.toString());
            getTableData();
        });

        //获取表格数据
        getTableData();

    }

    /**
     * 获取菜单数据
     */
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("create_time desc");
        }
        PageInfo<WMenu> pageInfo = PageHelper.startPage(queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy()).doSelectPageInfo(() ->
                wMenuDao.queryLike(queryBean.getQuery())
        );

        //总页数发生改变时从第一页开始
        if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
            queryBean.setPageNum(1);
            getTableData();
            return;
        }

        //一共多少条数据
        if(queryBean.getTotal()-pageInfo.getTotal()!=0){
            queryBean.setTotal(pageInfo.getTotal());
            totalLabel.setText(String.valueOf(queryBean.getTotal()));
        }

        //一共多少页
        if(queryBean.getPages()-pageInfo.getPages()!=0) {
            queryBean.setPages(pageInfo.getPages());
            pagesLabel.setText(String.valueOf(queryBean.getPages()));
            pagination.setPageCount(queryBean.getPages());
        }

        tableView.getItems().clear();
        if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty())
            tableView.getItems().addAll(pageInfo.getList());
    }

    /**
     * 初始化按钮监听
     */
    private void initButton() {
        //点击保存
        saveJFXButton.setOnAction(event -> {
            String menuName = menuNameTextField.getText();
            if(StringUtils.isEmpty(menuName)){
                return;
            }
            String menuUrl = menuUrlTextField.getText();
            if(StringUtils.isEmpty(menuUrl)){
                return;
            }
            int parentMenuId = parentMenuComboBox.getValue().getMenuId();
            selectMenu.setMenuName(menuName);
            selectMenu.setFxmlUrl(menuUrl);
            selectMenu.setParentMenuId(parentMenuId);

            Date now = new Date();

            selectMenu.setModifyTime(now);

            if(StringUtils.isEmpty(selectMenu.getMenuId())) {
                selectMenu.setCreateTime(now);
                wMenuDao.insert(selectMenu);
            }else {
                wMenuDao.update(selectMenu);

                WUserMenu where = new WUserMenu();
                where.setMenuId(selectMenu.getMenuId());
                WUserMenu set = new WUserMenu();
                set.setMenuName(selectMenu.getMenuName());
                set.setFxmlUrl(selectMenu.getFxmlUrl());
                set.setParentMenuId(selectMenu.getParentMenuId());
                set.setModifyTime(now);
                wUserMenuDao.updateByField(where, set);
            }

            getTableData();
            resetForm();
        });

        //点击删除
        delJFXButton.setOnAction(event -> {
            if(selectMenu!=null && StringUtils.isNotEmpty(selectMenu.getMenuId())){
                wMenuDao.deleteByEntity(selectMenu);
                getTableData();
            }
            resetForm();
        });

        //查询
        seachJFXButton.setOnAction(event -> {
            WMenu wMenu = new WMenu();
            String menuName = queryMenuNameTextField.getText();
            wMenu.setMenuName(menuName);
            String menuUrl = queryMenuUrlTextField.getText();
            wMenu.setFxmlUrl(menuUrl);
            int parentMenuId = queryParentMenuComboBox.getValue().getMenuId();
            if(parentMenuId!=-1)wMenu.setParentMenuId(parentMenuId);

            if(!modifyTimeStartPicker.isVoid())
                wMenu.setModifyTimeStart(DateUtil.localDateTime2Date(modifyTimeStart.get()));
            if(!modifyTimeEndPicker.isVoid())
                wMenu.setModifyTimeEnd(DateUtil.localDateTime2Date(modifyTimeEnd.get()));

            queryBean.setQuery(wMenu);
            getTableData();
        });
    }

    /**
     * 清空编辑区和selectMenu
     */
    private void resetForm() {
        menuNameTextField.clear();
        menuUrlTextField.clear();
        parentMenuComboBox.getSelectionModel().select(0);
        selectMenu.setMenuId(null);
    }

    @Override
    public void close() {

    }
}
